home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / test / test_cfgparser.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  8.2 KB  |  285 lines

  1. import ConfigParser
  2. import StringIO
  3.  
  4. from test_support import TestFailed, verify
  5.  
  6.  
  7. def basic(src):
  8.     print "Testing basic accessors..."
  9.     cf = ConfigParser.ConfigParser()
  10.     sio = StringIO.StringIO(src)
  11.     cf.readfp(sio)
  12.     L = cf.sections()
  13.     L.sort()
  14.     verify(L == [r'Commented Bar',
  15.                  r'Foo Bar',
  16.                  r'Internationalized Stuff',
  17.                  r'Long Line',
  18.                  r'Section\with$weird%characters[' '\t',
  19.                  r'Spaces',
  20.                  r'Spacey Bar',
  21.                  ],
  22.            "unexpected list of section names")
  23.  
  24.     # The use of spaces in the section names serves as a regression test for
  25.     # SourceForge bug #115357.
  26.     # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357
  27.     verify(cf.get('Foo Bar', 'foo', raw=1) == 'bar')
  28.     verify(cf.get('Spacey Bar', 'foo', raw=1) == 'bar')
  29.     verify(cf.get('Commented Bar', 'foo', raw=1) == 'bar')
  30.     verify(cf.get('Spaces', 'key with spaces', raw=1) == 'value')
  31.     verify(cf.get('Spaces', 'another with spaces', raw=1) == 'splat!')
  32.  
  33.     verify('__name__' not in cf.options("Foo Bar"),
  34.            '__name__ "option" should not be exposed by the API!')
  35.  
  36.     # Make sure the right things happen for remove_option();
  37.     # added to include check for SourceForge bug #123324:
  38.     verify(cf.remove_option('Foo Bar', 'foo'),
  39.            "remove_option() failed to report existance of option")
  40.     verify(not cf.has_option('Foo Bar', 'foo'),
  41.            "remove_option() failed to remove option")
  42.     verify(not cf.remove_option('Foo Bar', 'foo'),
  43.            "remove_option() failed to report non-existance of option"
  44.            " that was removed")
  45.     try:
  46.         cf.remove_option('No Such Section', 'foo')
  47.     except ConfigParser.NoSectionError:
  48.         pass
  49.     else:
  50.         raise TestFailed(
  51.             "remove_option() failed to report non-existance of option"
  52.             " that never existed")
  53.  
  54.     verify(cf.get('Long Line', 'foo', raw=1) ==
  55.            'this line is much, much longer than my editor\nlikes it.')
  56.  
  57.  
  58. def write(src):
  59.     print "Testing writing of files..."
  60.     cf = ConfigParser.ConfigParser()
  61.     sio = StringIO.StringIO(src)
  62.     cf.readfp(sio)
  63.     output = StringIO.StringIO()
  64.     cf.write(output)
  65.     verify(output, """[DEFAULT]
  66. foo = another very
  67.         long line
  68.  
  69. [Long Line]
  70. foo = this line is much, much longer than my editor
  71.         likes it.
  72. """)
  73.  
  74. def case_sensitivity():
  75.     print "Testing case sensitivity..."
  76.     cf = ConfigParser.ConfigParser()
  77.     cf.add_section("A")
  78.     cf.add_section("a")
  79.     L = cf.sections()
  80.     L.sort()
  81.     verify(L == ["A", "a"])
  82.     cf.set("a", "B", "value")
  83.     verify(cf.options("a") == ["b"])
  84.     verify(cf.get("a", "b", raw=1) == "value",
  85.            "could not locate option, expecting case-insensitive option names")
  86.     verify(cf.has_option("a", "b"))
  87.     cf.set("A", "A-B", "A-B value")
  88.     for opt in ("a-b", "A-b", "a-B", "A-B"):
  89.         verify(cf.has_option("A", opt),
  90.                "has_option() returned false for option which should exist")
  91.     verify(cf.options("A") == ["a-b"])
  92.     verify(cf.options("a") == ["b"])
  93.     cf.remove_option("a", "B")
  94.     verify(cf.options("a") == [])
  95.  
  96.     # SF bug #432369:
  97.     cf = ConfigParser.ConfigParser()
  98.     sio = StringIO.StringIO("[MySection]\nOption: first line\n\tsecond line\n")
  99.     cf.readfp(sio)
  100.     verify(cf.options("MySection") == ["option"])
  101.     verify(cf.get("MySection", "Option") == "first line\nsecond line")
  102.  
  103.     # SF bug #561822:
  104.     cf = ConfigParser.ConfigParser(defaults={"key":"value"})
  105.     cf.readfp(StringIO.StringIO("[section]\nnekey=nevalue\n"))
  106.     verify(cf.has_option("section", "Key"))
  107.  
  108.  
  109. def boolean(src):
  110.     print "Testing interpretation of boolean Values..."
  111.     cf = ConfigParser.ConfigParser()
  112.     sio = StringIO.StringIO(src)
  113.     cf.readfp(sio)
  114.     for x in range(1, 5):
  115.         verify(cf.getboolean('BOOLTEST', 't%d' % (x)) == 1)
  116.     for x in range(1, 5):
  117.         verify(cf.getboolean('BOOLTEST', 'f%d' % (x)) == 0)
  118.     for x in range(1, 5):
  119.         try:
  120.             cf.getboolean('BOOLTEST', 'e%d' % (x))
  121.         except ValueError:
  122.             pass
  123.         else:
  124.             raise TestFailed(
  125.                 "getboolean() failed to report a non boolean value")
  126.  
  127.  
  128. def interpolation(src):
  129.     print "Testing value interpolation..."
  130.     cf = ConfigParser.ConfigParser({"getname": "%(__name__)s"})
  131.     sio = StringIO.StringIO(src)
  132.     cf.readfp(sio)
  133.     verify(cf.get("Foo", "getname") == "Foo")
  134.     verify(cf.get("Foo", "bar") == "something with interpolation (1 step)")
  135.     verify(cf.get("Foo", "bar9")
  136.            == "something with lots of interpolation (9 steps)")
  137.     verify(cf.get("Foo", "bar10")
  138.            == "something with lots of interpolation (10 steps)")
  139.     expect_get_error(cf, ConfigParser.InterpolationDepthError, "Foo", "bar11")
  140.  
  141.  
  142. def parse_errors():
  143.     print "Testing parse errors..."
  144.     expect_parse_error(ConfigParser.ParsingError,
  145.                        """[Foo]\n  extra-spaces: splat\n""")
  146.     expect_parse_error(ConfigParser.ParsingError,
  147.                        """[Foo]\n  extra-spaces= splat\n""")
  148.     expect_parse_error(ConfigParser.ParsingError,
  149.                        """[Foo]\noption-without-value\n""")
  150.     expect_parse_error(ConfigParser.ParsingError,
  151.                        """[Foo]\n:value-without-option-name\n""")
  152.     expect_parse_error(ConfigParser.ParsingError,
  153.                        """[Foo]\n=value-without-option-name\n""")
  154.     expect_parse_error(ConfigParser.MissingSectionHeaderError,
  155.                        """No Section!\n""")
  156.  
  157.  
  158. def query_errors():
  159.     print "Testing query interface..."
  160.     cf = ConfigParser.ConfigParser()
  161.     verify(cf.sections() == [],
  162.            "new ConfigParser should have no defined sections")
  163.     verify(not cf.has_section("Foo"),
  164.            "new ConfigParser should have no acknowledged sections")
  165.     try:
  166.         cf.options("Foo")
  167.     except ConfigParser.NoSectionError, e:
  168.         pass
  169.     else:
  170.         raise TestFailed(
  171.             "Failed to catch expected NoSectionError from options()")
  172.     try:
  173.         cf.set("foo", "bar", "value")
  174.     except ConfigParser.NoSectionError, e:
  175.         pass
  176.     else:
  177.         raise TestFailed("Failed to catch expected NoSectionError from set()")
  178.     expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar")
  179.     cf.add_section("foo")
  180.     expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
  181.  
  182.  
  183. def weird_errors():
  184.     print "Testing miscellaneous error conditions..."
  185.     cf = ConfigParser.ConfigParser()
  186.     cf.add_section("Foo")
  187.     try:
  188.         cf.add_section("Foo")
  189.     except ConfigParser.DuplicateSectionError, e:
  190.         pass
  191.     else:
  192.         raise TestFailed("Failed to catch expected DuplicateSectionError")
  193.  
  194.  
  195. def expect_get_error(cf, exctype, section, option, raw=0):
  196.     try:
  197.         cf.get(section, option, raw=raw)
  198.     except exctype, e:
  199.         pass
  200.     else:
  201.         raise TestFailed("Failed to catch expected " + exctype.__name__)
  202.  
  203.  
  204. def expect_parse_error(exctype, src):
  205.     cf = ConfigParser.ConfigParser()
  206.     sio = StringIO.StringIO(src)
  207.     try:
  208.         cf.readfp(sio)
  209.     except exctype, e:
  210.         pass
  211.     else:
  212.         raise TestFailed("Failed to catch expected " + exctype.__name__)
  213.  
  214.  
  215. basic(r"""
  216. [Foo Bar]
  217. foo=bar
  218. [Spacey Bar]
  219. foo = bar
  220. [Commented Bar]
  221. foo: bar ; comment
  222. [Long Line]
  223. foo: this line is much, much longer than my editor
  224.    likes it.
  225. [Section\with$weird%characters[""" '\t' r"""]
  226. [Internationalized Stuff]
  227. foo[bg]: Bulgarian
  228. foo=Default
  229. foo[en]=English
  230. foo[de]=Deutsch
  231. [Spaces]
  232. key with spaces : value
  233. another with spaces = splat!
  234. """)
  235. write("""[Long Line]
  236. foo: this line is much, much longer than my editor
  237.    likes it.
  238. [DEFAULT]
  239. foo: another very
  240.  long line""")
  241. case_sensitivity()
  242. boolean(r"""
  243. [BOOLTEST]
  244. T1=1
  245. T2=TRUE
  246. T3=True
  247. T4=oN
  248. T5=yes
  249. F1=0
  250. F2=FALSE
  251. F3=False
  252. F4=oFF
  253. F5=nO
  254. E1=2
  255. E2=foo
  256. E3=-1
  257. E4=0.1
  258. E5=FALSE AND MORE
  259. """)
  260. interpolation(r"""
  261. [Foo]
  262. bar=something %(with1)s interpolation (1 step)
  263. bar9=something %(with9)s lots of interpolation (9 steps)
  264. bar10=something %(with10)s lots of interpolation (10 steps)
  265. bar11=something %(with11)s lots of interpolation (11 steps)
  266. with11=%(with10)s
  267. with10=%(with9)s
  268. with9=%(with8)s
  269. with8=%(with7)s
  270. with7=%(with6)s
  271. with6=%(with5)s
  272. with5=%(with4)s
  273. with4=%(with3)s
  274. with3=%(with2)s
  275. with2=%(with1)s
  276. with1=with
  277.  
  278. [Mutual Recursion]
  279. foo=%(bar)s
  280. bar=%(foo)s
  281. """)
  282. parse_errors()
  283. query_errors()
  284. weird_errors()
  285.